﻿namespace WebPacker.Packs.Watchers
{
	using System;
	using WebPacker.Logger;
	using WebPacker.Packs.Resources;

	public class ContentWatcher : BaseResourceWatcher
	{
		private readonly EventHandler onChanged;

		public ContentWatcher()
		{
			onChanged = new EventHandler(OnChanged);
		}

		public override event EventHandler<ResourceChangedEventArgs> Changed;

		public override bool Accept(IResource resource)
		{
			return resource is ContentResource;
		}

		protected override void Watch(IResource resource)
		{
			((ContentResource)resource).OnChanged += onChanged;
		}

		protected override void Unwatch(IResource resource)
		{
			((ContentResource)resource).OnChanged -= onChanged;
		}

		private void OnChanged(object sender, EventArgs e)
		{
			if (Changed != null)
			{
				ContentResource resource = null;

				try
				{
					resource = (ContentResource)sender;
					LogFactory.GetLogger().Info(() => string.Format("Resource \"{0}\" is changed.", resource.Name));
					Changed(this, new ResourceChangedEventArgs(resource.Name, new[] { resource }));
				}
				catch (Exception ex)
				{
					LogFactory.GetLogger().Exception(string.Format("Error at process change of resource \"{0}\".", resource != null ? resource.Name : null), ex);
				}
			}
		}
	}
}